import { BadRequestException, Controller, Post, Req, UploadedFile } from '@nestjs/common';
import { ApiBody, ApiConsumes, ApiOperation, ApiTags, ApiExcludeController } from '@nestjs/swagger';
import { FastifyRequest } from 'fastify';

import { ApiSecurityAuth } from '~/common/decorators/swagger.decorator';

import { Perm, definePermission } from '~/modules/auth/decorators/permission.decorator';

import { FileUploadDto } from './upload.dto';
import { UploadService } from './upload.service';
import { Public } from '~/modules/auth/decorators/public.decorator';
import { ModuleSwaggerTags } from '~/constants/modules.constant';

export const permissions = definePermission('upload', {
  UPLOAD: 'upload',
} as const);

@Public()
@ApiSecurityAuth()
@ApiTags(ModuleSwaggerTags.UPLOAD)
@Controller('upload')
export class UploadController {
  constructor(private uploadService: UploadService) {}

  @Post()
  // @Perm(permissions.UPLOAD)
  @ApiOperation({ summary: '上传' })
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    type: FileUploadDto,
  })
  async upload(@Req() req: FastifyRequest) {

    try {
			const fields: Record<string, any> = req.body; // 获取单个文件

			const file = fields.file; // 获取表单字段

			if (!file) {
				throw new BadRequestException('文件不能为空')
			}

      const path = await this.uploadService.saveFdfsFile(file)

      return path;
    }
    catch (error) {
      console.log(error)
      throw new BadRequestException('上传失败')
    }
  }
}
